<?php
/**
 * Created by ModelCreater.
 * Date: 2023-09-22
 * Time: 17:29:50
 */

namespace model;

use Carbon\Carbon;
use lib\common\CommonModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;
use think\model\concern\SoftDelete;

class AdminPermissionUserModel extends CommonModel
{


    protected $table = 'admin_permission_user';

    protected $autoWriteTimestamp = 'datetime';
    protected $createTime = 'create_time';
    protected $updateTime = false;

    protected $schema = [
        'permission_id' => 'int',
        'user_id'       => 'int',
        'create_time'   => 'datetime',
    ];

    /**
     * 获取管理员权限
     * @param int $userId
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getUserPermission (int $userId): array {
        $permissionIdSql = $this->where('user_id', $userId)->field('permission_id')->buildSql();
        return make(AdminPermissionModel::class)->where('id', 'in', Db::raw($permissionIdSql))->order(['id' => 'ASC'])->select()->toArray();
    }

    public function saveBatch ($userId, $permissions): void {
        $now = Carbon::now()->toDateTimeString();
        $permissions = array_map(function ($item) use ($now, $userId) {
            return [
                'permission_id' => $item,
                'user_id'       => $userId,
                'create_time'   => $now
            ];
        }, $permissions);
        $this->insertAll($permissions);
    }
}
